package com.uzai.console.service.main.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.aliyun.dingtalkservice_group_1_0.models.CreateGroupHeaders;
import com.aliyun.dingtalkservice_group_1_0.models.CreateGroupRequest;
import com.aliyun.dingtalkservice_group_1_0.models.CreateGroupResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.device.DeviceInfoMobileWeChatCacheDto;
import com.uzai.common.dto.device.DeviceInfoMobileWxWorkCacheDto;
import com.uzai.common.dto.device.DeviceInfoPcWeChatCacheDto;
import com.uzai.common.dto.device.DeviceInfoWxWorkCacheDto;
import com.uzai.common.dto.god.ExclusiveGroupOptDto;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DingExclusiveGroupUtils;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.alipaydetail.AlipayDetailCreateDto;
import com.uzai.console.dto.alipaydetail.TransUniTransferDto;
import com.uzai.console.dto.device.deviceauth.DeviceAuthQuery;
import com.uzai.console.dto.feign.report.RealTimeOverviewReportFeignDto;
import com.uzai.console.dto.main.main.*;
import com.uzai.console.dto.report.RealTimeOverviewReportDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.dto.wechatprivate.friendrequest.FriendRequestQuery;
import com.uzai.console.dto.wechatwork.devicewxworkinfo.DeviceWxworkInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.alipaydetail.AlipayDetailService;
import com.uzai.console.service.feign.UzaiReportServerFeignService;
import com.uzai.console.service.main.MainService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.report.RealTimeOverviewReportService;
import com.uzai.console.service.wechatprivate.FriendRequestService;
import com.uzai.console.vo.alipaydetail.businessinfo.RechargeBusinessInfo;
import com.uzai.console.vo.alipaydetail.businessinfo.TakeBalBusinessInfo;
import com.uzai.console.vo.main.main.*;
import com.uzai.console.vo.report.RealTimeOverviewReportVo;
import com.uzai.console.vo.report.RealTimeOverviewResultVo;
import com.uzai.console.vo.wechatprivate.friendrequest.FriendRequestInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class MainServiceImpl implements MainService {

    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MainMapper mainMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private ProductPriceMapper productPriceMapper;
    @Autowired
    private ProductAuthMapper productAuthMapper;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private FriendRequestService friendRequestService;
    @Autowired
    private AlipayDetailService alipayDetailService;
    @Autowired
    private AlipayDetailMapper alipayDetailMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private DevicePriceMapper devicePriceMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private com.aliyun.dingtalkservice_group_1_0.Client dingGroupClient;
    @Autowired
    private com.aliyun.dingtalkoauth2_1_0.Client dingTokenClient;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private RealTimeOverviewReportService realTimeOverviewReportService;
    @Autowired
    private DingExclusiveGroupUtils dingExclusiveGroupUtils;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UzaiReportServerFeignService uzaiReportServerFeignService;

    /**
     * 查询账户余额
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public BalanceVo findBalance(Long merId){
        BalanceVo balanceVo = new BalanceVo();
        Merchant merchant = merchantMapper.selectById(merId);
        if(merchant != null){
            balanceVo.setBalance(Tools.getDouble(merchant.getBalance()));
            balanceVo.setName(merchant.getName());
        }
        return balanceVo;
    }

    /**
     * 机器人总数
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public DeviceCountVo findDeviceCount(Long merId){
        DeviceCountVo deviceCountVo = new DeviceCountVo();

        //个微机器人总数
        int deviceWechatCount = 0;
        //个微机器人在线总数
        int deviceWechatOnlineCount = 0;

        //企微机器人总数
        int deviceWxworkCount = 0;
        //企微机器人在线总数
        int deviceWxworkOnlineCount = 0;

        //稳定运行天数
        int runDays = 0;

        //个人微信机器人数量
        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
        deviceWechatInfoQuery.setMerId(merId);
        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
            //机器人总数
            deviceWechatCount = deviceWechatInfoList.size();

            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList){
                //从缓存redis中查询机器人的心跳信息
                boolean onlineFlag = false; //在线标志
                //从缓存中换取个人微信PC端信息
                Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoPcWeChatCacheDto.class);
                //手机端个人微信信息不为空
                if(deviceInfoPcWeChatCacheDto != null){
                    //获取最新心跳时间
                    Integer lastHeartBeatTime = deviceInfoPcWeChatCacheDto.getLastHeartBeatTime();
                    if(lastHeartBeatTime != null){
                        //判断在线（少于5分钟表示在线）
                        if(DateUtil.getNowTime() - lastHeartBeatTime  < Const.Device.HEART_BEAT_OFF_LINE_TIME){
                            onlineFlag = true; //在线
                        }
                    }
                }

                //从缓存中获取个人微信手机端信息
                Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWeChatCacheDto.class);
                //手机端个人微信信息不为空
                if(deviceInfoMobileWeChatCacheDto != null){
                    //获取最新心跳时间
                    Integer lastHeartBeatTime = deviceInfoMobileWeChatCacheDto.getLastHeartBeatTime();
                    if(lastHeartBeatTime != null){
                        //判断在线（少于5分钟表示在线）
                        if(DateUtil.getNowTime() - lastHeartBeatTime  < Const.Device.HEART_BEAT_OFF_LINE_TIME){
                            onlineFlag = true; //在线
                        }
                    }
                }
                //机器人在线，则在线机器人数+1
                if(onlineFlag){
                    deviceWechatOnlineCount ++ ; //
                }
            }
        }

        //企业微信机器人数量
        DeviceWxworkInfoQuery deviceWxworkInfoQuery = new DeviceWxworkInfoQuery();
        deviceWxworkInfoQuery.setMerId(merId);
        List<DeviceWxworkInfo> deviceWxworkInfoList = deviceWxworkInfoMapper.findByList(deviceWxworkInfoQuery);
        if(deviceWxworkInfoList != null && deviceWxworkInfoList.size() > 0){
            //机器人总数
            deviceWxworkCount = deviceWxworkInfoList.size();

            for (DeviceWxworkInfo deviceWxworkInfo : deviceWxworkInfoList){
                //从缓存redis中查询Pc端企微机器人的心跳信息
                boolean onlineFlag = false; //在线标志
                //从缓存中换取个人微信PC端信息
                Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
                DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoWxWorkCacheDto.class);
                //手机端个人微信信息不为空
                if(deviceInfoWxWorkCacheDto != null){
                    //获取最新心跳时间
                    Integer lastHeartBeatTime = deviceInfoWxWorkCacheDto.getLastHeartBeatTime();
                    if(lastHeartBeatTime != null){
                        //判断在线（少于5分钟表示在线）
                        if(DateUtil.getNowTime() - lastHeartBeatTime  < Const.Device.HEART_BEAT_OFF_LINE_TIME){
                            onlineFlag = true; //在线
                        }
                    }
                }

                //从缓存redis中查询移动端企微机器人的心跳信息
                Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWxWorkCacheDto.class);
                //手机端个人微信信息不为空
                if(deviceInfoMobileWxWorkCacheDto != null){
                    //获取最新心跳时间
                    Integer lastHeartBeatTime = deviceInfoMobileWxWorkCacheDto.getLastHeartBeatTime();
                    if(lastHeartBeatTime != null){
                        //判断在线（少于5分钟表示在线）
                        if(DateUtil.getNowTime() - lastHeartBeatTime  < Const.Device.HEART_BEAT_OFF_LINE_TIME){
                            onlineFlag = true; //在线
                        }
                    }
                }


                //机器人在线，则在线机器人数+1
                if(onlineFlag){
                    deviceWxworkOnlineCount ++ ; //
                }
            }
        }

        //机器人总数
        int deviceCount = deviceWechatCount + deviceWxworkCount;
        //机器人在线总数
        int deviceOnlineCount = deviceWechatOnlineCount + deviceWxworkOnlineCount;

        //稳定运行天数
        Merchant merchant = merchantMapper.selectById(merId);
        if(merchant != null){
            Integer createTime = Tools.getInteger(merchant.getCreateTime());
            runDays = (DateUtil.getNowTime() - createTime) / (24 * 3600);
        }

        //机器人数量统计
        deviceCountVo.setDeviceCount(deviceCount);
        deviceCountVo.setDeviceOnlineCount(deviceOnlineCount);
        //个微机器人数量统计
        deviceCountVo.setDeviceWechatCount(deviceWechatCount);
        deviceCountVo.setDeviceWechatOnlineCount(deviceWechatOnlineCount);
        //企微机器人数量统计
        deviceCountVo.setDeviceWxworkCount(deviceWxworkCount);
        deviceCountVo.setDeviceWxworkOnlineCount(deviceWxworkOnlineCount);

        //稳定运行天数
        deviceCountVo.setRunDays(runDays);

        return deviceCountVo;
    }

    /**
     * 查询订单统计
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public ProfitVo findProfit(Long merId){
        //返回页面字段
        ProfitVo profitVo = new ProfitVo();

        //本月预估利润
        double profitMonth = 0.00D;
        //今天预估利润
        double profitToday = 0.00D;
        //昨天预估利润
        double profitYesterday = 0.00D;
        //本月有效订单数
        int validOrderCountMonth = 0;
        //今天有效订单数
        int validOrderCountToday = 0;
        //昨天有效订单数
        int validOrderCountYesterday = 0;
        //今日新增会员
        int newUserCountToday = 0;
        //昨日新增会员
        int newUserCountYesterday = 0;
        //本月新增会员
        int newUserCountMonth = 0;
        //本月提现总金额
        double takeBalMonth = 0.00D;
        //今天提现总金额
        double takeBalToday = 0.00D;
        //昨天提现总金额
        double takeBalYesterday = 0.00D;


        //个人微信
        if(true){
            RealTimeOverviewReportDto realTimeOverviewReportDto = new RealTimeOverviewReportDto();
            realTimeOverviewReportDto.setMerId(merId);
            realTimeOverviewReportDto.setPlatformType(0); //全部平台
            realTimeOverviewReportDto.setDeviceType("private_wechat"); //个人微信
            RealTimeOverviewResultVo realTimeOverviewResultVo = realTimeOverviewReportService.realTimeOverviewReport(realTimeOverviewReportDto);
            //今日统计
            RealTimeOverviewReportVo today = realTimeOverviewResultVo.getToday();
            //昨天统计
            RealTimeOverviewReportVo yesterday = realTimeOverviewResultVo.getYesterday();
            //本月统计
            RealTimeOverviewReportVo currentMonth = realTimeOverviewResultVo.getCurrentMonth();
            //今天预估利润
            profitToday = com.uzai.common.utils.Math.add(Tools.getDouble(today.getTotalEstimateProfit()), profitToday);
            //昨天预估利润
            profitYesterday = com.uzai.common.utils.Math.add(Tools.getDouble(yesterday.getTotalEstimateProfit()), profitYesterday);
            //本月预估利润
            profitMonth = com.uzai.common.utils.Math.add(Tools.getDouble(currentMonth.getTotalEstimateProfit()), profitMonth);

            //今天有效订单数
            validOrderCountToday = Tools.getInteger(today.getTotalValidOrderCount()) + validOrderCountToday;
            //昨天有效订单数
            validOrderCountYesterday = Tools.getInteger(yesterday.getTotalValidOrderCount()) + validOrderCountYesterday;
            //本月有效订单数
            validOrderCountMonth = Tools.getInteger(currentMonth.getTotalValidOrderCount()) + validOrderCountMonth;

            //今日新增会员
            newUserCountToday = Tools.getInteger(today.getNewUserCount()) + newUserCountToday;
            //昨日新增会员
            newUserCountYesterday = Tools.getInteger(yesterday.getNewUserCount()) + newUserCountYesterday;
            //本月新增会员
            newUserCountMonth = Tools.getInteger(currentMonth.getNewUserCount()) + newUserCountMonth;

            //今日提现金额
            takeBalToday = com.uzai.common.utils.Math.add(Tools.getDouble(today.getWithdrawalTotalBalance()), takeBalToday);
            //昨日提现金额
            takeBalYesterday = com.uzai.common.utils.Math.add(Tools.getDouble(yesterday.getWithdrawalTotalBalance()), takeBalYesterday);
            //本月提现金额
            takeBalMonth = com.uzai.common.utils.Math.add(Tools.getDouble(currentMonth.getWithdrawalTotalBalance()), takeBalMonth);
        }

        //企业微信
        if(true){
            RealTimeOverviewReportDto realTimeOverviewReportDto = new RealTimeOverviewReportDto();
            realTimeOverviewReportDto.setMerId(merId);
            realTimeOverviewReportDto.setPlatformType(0); //全部平台
            realTimeOverviewReportDto.setDeviceType("work_wechat"); //企业微信
            RealTimeOverviewResultVo realTimeOverviewResultVo = realTimeOverviewReportService.realTimeOverviewReport(realTimeOverviewReportDto);
            //今日统计
            RealTimeOverviewReportVo today = realTimeOverviewResultVo.getToday();
            //昨天统计
            RealTimeOverviewReportVo yesterday = realTimeOverviewResultVo.getYesterday();
            //本月统计
            RealTimeOverviewReportVo currentMonth = realTimeOverviewResultVo.getCurrentMonth();
            //今天预估利润
            profitToday = com.uzai.common.utils.Math.add(Tools.getDouble(today.getTotalEstimateProfit()), profitToday);
            //昨天预估利润
            profitYesterday = com.uzai.common.utils.Math.add(Tools.getDouble(yesterday.getTotalEstimateProfit()), profitYesterday);
            //本月预估利润
            profitMonth = com.uzai.common.utils.Math.add(Tools.getDouble(currentMonth.getTotalEstimateProfit()), profitMonth);

            //今天有效订单数
            validOrderCountToday = Tools.getInteger(today.getTotalValidOrderCount()) + validOrderCountToday;
            //昨天有效订单数
            validOrderCountYesterday = Tools.getInteger(yesterday.getTotalValidOrderCount()) + validOrderCountYesterday;
            //本月有效订单数
            validOrderCountMonth = Tools.getInteger(currentMonth.getTotalValidOrderCount()) + validOrderCountMonth;

            //今日新增会员
            newUserCountToday = Tools.getInteger(today.getNewUserCount()) + newUserCountToday;
            //昨日新增会员
            newUserCountYesterday = Tools.getInteger(yesterday.getNewUserCount()) + newUserCountYesterday;
            //本月新增会员
            newUserCountMonth = Tools.getInteger(currentMonth.getNewUserCount()) + newUserCountMonth;

            //今日提现金额
            takeBalToday = com.uzai.common.utils.Math.add(Tools.getDouble(today.getWithdrawalTotalBalance()), takeBalToday);
            //昨日提现金额
            takeBalYesterday = com.uzai.common.utils.Math.add(Tools.getDouble(yesterday.getWithdrawalTotalBalance()), takeBalYesterday);
            //本月提现金额
            takeBalMonth = com.uzai.common.utils.Math.add(Tools.getDouble(currentMonth.getWithdrawalTotalBalance()), takeBalMonth);
        }

        //公众号
        if(true){
            RealTimeOverviewReportDto realTimeOverviewReportDto = new RealTimeOverviewReportDto();
            realTimeOverviewReportDto.setMerId(merId);
            realTimeOverviewReportDto.setPlatformType(0); //全部平台
            realTimeOverviewReportDto.setDeviceType("wx_pub"); //公众号
            RealTimeOverviewResultVo realTimeOverviewResultVo = realTimeOverviewReportService.realTimeOverviewReport(realTimeOverviewReportDto);
            //今日统计
            RealTimeOverviewReportVo today = realTimeOverviewResultVo.getToday();
            //昨天统计
            RealTimeOverviewReportVo yesterday = realTimeOverviewResultVo.getYesterday();
            //本月统计
            RealTimeOverviewReportVo currentMonth = realTimeOverviewResultVo.getCurrentMonth();
            //今天预估利润
            profitToday = com.uzai.common.utils.Math.add(Tools.getDouble(today.getTotalEstimateProfit()), profitToday);
            //昨天预估利润
            profitYesterday = com.uzai.common.utils.Math.add(Tools.getDouble(yesterday.getTotalEstimateProfit()), profitYesterday);
            //本月预估利润
            profitMonth = com.uzai.common.utils.Math.add(Tools.getDouble(currentMonth.getTotalEstimateProfit()), profitMonth);

            //今天有效订单数
            validOrderCountToday = Tools.getInteger(today.getTotalValidOrderCount()) + validOrderCountToday;
            //昨天有效订单数
            validOrderCountYesterday = Tools.getInteger(yesterday.getTotalValidOrderCount()) + validOrderCountYesterday;
            //本月有效订单数
            validOrderCountMonth = Tools.getInteger(currentMonth.getTotalValidOrderCount()) + validOrderCountMonth;

            //今日新增会员
            newUserCountToday = Tools.getInteger(today.getNewUserCount()) + newUserCountToday;
            //昨日新增会员
            newUserCountYesterday = Tools.getInteger(yesterday.getNewUserCount()) + newUserCountYesterday;
            //本月新增会员
            newUserCountMonth = Tools.getInteger(currentMonth.getNewUserCount()) + newUserCountMonth;

            //今日提现金额
            takeBalToday = com.uzai.common.utils.Math.add(Tools.getDouble(today.getWithdrawalTotalBalance()), takeBalToday);
            //昨日提现金额
            takeBalYesterday = com.uzai.common.utils.Math.add(Tools.getDouble(yesterday.getWithdrawalTotalBalance()), takeBalYesterday);
            //本月提现金额
            takeBalMonth = com.uzai.common.utils.Math.add(Tools.getDouble(currentMonth.getWithdrawalTotalBalance()), takeBalMonth);
        }

        profitVo.setProfitMonth(profitMonth);
        profitVo.setProfitToday(profitToday);
        profitVo.setProfitYesterday(profitYesterday);

        profitVo.setValidOrderCountMonth(validOrderCountMonth);
        profitVo.setValidOrderCountToday(validOrderCountToday);
        profitVo.setValidOrderCountYesterday(validOrderCountYesterday);

        profitVo.setNewUserCountToday(newUserCountToday);
        profitVo.setNewUserCountYesterday(newUserCountYesterday);
        profitVo.setNewUserCountMonth(newUserCountMonth);

        profitVo.setTakeBalMonth(takeBalMonth);
        profitVo.setTakeBalToday(takeBalToday);
        profitVo.setTakeBalYesterday(takeBalYesterday);

        return profitVo;

    }

    /**
     * 查询新增用户
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public UserAddVo findUserAdd(Long merId){
        UserAddVo userAddVo = new UserAddVo();

        //获取本月第一天
        String month = DateUtil.getEndDayOrOneDay(new Date(),0);
        //本月第一天的开始时间戳
        Integer monthStart = DateUtil.getStrTime(month + " 00:00:00");
        UserAddDto userAddDto_month = new UserAddDto();
        userAddDto_month.setMonthStart(monthStart);
        userAddDto_month.setMerId(merId);

        //今天
        String today = Tools.getDateMonthDayStrTwo();
        //今天的开始时间戳
        Integer todayStart = DateUtil.getStrTime(today + " 00:00:00");
        UserAddDto userAddDto_today = new UserAddDto();
        userAddDto_today.setTodayStart(todayStart);
        userAddDto_today.setMerId(merId);

        //昨天
        String yesterday = Tools.getYesterdayDateStr();
        //昨天开始时间
        Integer yesterdayStart = DateUtil.getStrTime(yesterday + " 00:00:00");
        //昨天的结束时间
        Integer yesterdayEnd = DateUtil.getStrTime(yesterday + " 23:59:59");
        UserAddDto userAddDto_yesterday = new UserAddDto();
        userAddDto_yesterday.setYesterdayStart(yesterdayStart);
        userAddDto_yesterday.setYesterdayEnd(yesterdayEnd);
        userAddDto_yesterday.setMerId(merId);

        //查询本月新增用户
        Integer userAddCount_month = mainMapper.userAddReport(userAddDto_month);
        //查询今天新增用户
        Integer userAddCount_today = mainMapper.userAddReport(userAddDto_today);
        //查询昨天新增用户
        Integer userAddCount_yesterday = mainMapper.userAddReport(userAddDto_yesterday);

        userAddVo.setCountMonth(Tools.getInteger(userAddCount_month));
        userAddVo.setCountToday(Tools.getInteger(userAddCount_today));
        userAddVo.setCountYesterday(Tools.getInteger(userAddCount_yesterday));

        return userAddVo;
    }

    /**
     * 查询会员提现金额
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public UserTakeBalVo findUserTakeBal(Long merId){
        UserTakeBalVo userTakeBalVo = new UserTakeBalVo();

        //获取本月第一天
        String month = DateUtil.getEndDayOrOneDay(new Date(),0);
        //本月第一天的开始时间戳
        Integer monthStart = DateUtil.getStrTime(month + " 00:00:00");
        UserTakeBalDto userTakeBalDto_month = new UserTakeBalDto();
        userTakeBalDto_month.setMonthStart(monthStart);
        userTakeBalDto_month.setMerId(merId);
        userTakeBalDto_month.setType(1);//成功提现

        //今天
        String today = Tools.getDateMonthDayStrTwo();
        //今天的开始时间戳
        Integer todayStart = DateUtil.getStrTime(today + " 00:00:00");
        UserTakeBalDto userTakeBalDto_today = new UserTakeBalDto();
        userTakeBalDto_today.setTodayStart(todayStart);
        userTakeBalDto_today.setMerId(merId);
        userTakeBalDto_today.setType(1);//成功提现

        //昨天
        String yesterday = Tools.getYesterdayDateStr();
        //昨天开始时间
        Integer yesterdayStart = DateUtil.getStrTime(yesterday + " 00:00:00");
        //昨天的结束时间
        Integer yesterdayEnd = DateUtil.getStrTime(yesterday + " 23:59:59");
        UserTakeBalDto userTakeBalDto_yesterday = new UserTakeBalDto();
        userTakeBalDto_yesterday.setYesterdayStart(yesterdayStart);
        userTakeBalDto_yesterday.setYesterdayEnd(yesterdayEnd);
        userTakeBalDto_yesterday.setMerId(merId);
        userTakeBalDto_yesterday.setType(1);//成功提现

        //查询本月提现金额
        Double userAddCount_month = mainMapper.userTakeBalReport(userTakeBalDto_month);
        //查询今天提现金额
        Double userAddCount_today = mainMapper.userTakeBalReport(userTakeBalDto_today);
        //查询昨天提现金额
        Double userAddCount_yesterday = mainMapper.userTakeBalReport(userTakeBalDto_yesterday);

        userTakeBalVo.setTotalMonth(Tools.getDouble(userAddCount_month));
        userTakeBalVo.setTotalToday(Tools.getDouble(userAddCount_today));
        userTakeBalVo.setTotalYesterday(Tools.getDouble(userAddCount_yesterday));

        return userTakeBalVo;
    }

    /**
     * 查询授权即将到期数（7天内）
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public TokenVo findTokenExpired(Long merId){
        TokenVo tokenVo = new TokenVo();
        //查询运营商开启的产品功能模块
        Object productSwitch = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.PRODUCT_SWITCH.getKey(), merId));
        if(productSwitch != null){
            JSONArray productAuthArray = JSONObject.parseArray(productSwitch.toString());
            if(productAuthArray != null && productAuthArray.size() > 0){
                //当前时间
                Integer now = DateUtil.getNowTime();
                //即将到期数(7天）
                Integer expiringTime = now + 7*24*3600 ;

                if(productAuthArray.contains(ProductKeyEnum.TB.getValue())){
                    //淘宝授权到期数
                    Integer tbTokenExpirdCount = mainMapper.tbTokenExpiredCount(merId, now);
                    tokenVo.setTbTokenExpiredCount(Tools.getInteger(tbTokenExpirdCount));
                    Integer tbTokenExpiringCount = mainMapper.tbTokenExpiredCount(merId, expiringTime);
                    tokenVo.setTbTokenExpiringCount(Tools.getInteger(tbTokenExpiringCount) - Tools.getInteger(tbTokenExpirdCount));
                }
                if(productAuthArray.contains(ProductKeyEnum.LOCAL_LIVE.getValue())){
                    //饿了么授权到期数
                    //Integer elmTokenExpirdCount = mainMapper.elmTokenExpiredCount(merId, now);
                    //tokenVo.setElmTokenExpiredCount(Tools.getInteger(elmTokenExpirdCount));
                    //饿了么授权即将期数
                    //Integer elmTokenExpiringCount = mainMapper.elmTokenExpiredCount(merId, expiringTime);
                    //tokenVo.setElmTokenExpiringCount(Tools.getInteger(elmTokenExpiringCount)-Tools.getInteger(elmTokenExpirdCount));
                }
                if(productAuthArray.contains(ProductKeyEnum.PDD.getValue())){
                    //拼多多授权到期数
                    Integer pddTokenExpirdCount = mainMapper.pddTokenExpiredCount(merId, now);
                    tokenVo.setPddTokenExpiredCount(Tools.getInteger(pddTokenExpirdCount));
                    //拼多多授权即将到期数
                    Integer pddTokenExpiringCount = mainMapper.pddTokenExpiredCount(merId, expiringTime);
                    tokenVo.setPddTokenExpiringCount(Tools.getInteger(pddTokenExpiringCount) - Tools.getInteger(pddTokenExpirdCount));
                }
                if(productAuthArray.contains(ProductKeyEnum.VPH.getValue())){
                    //唯品会授权到期数
                    Integer vphTokenExpirdCount = mainMapper.vphTokenExpiredCount(merId, now);
                    tokenVo.setVphTokenExpiredCount(Tools.getInteger(vphTokenExpirdCount));
                    //唯品会授权即将到期数
                    Integer vphTokenExpiringCount = mainMapper.vphTokenExpiredCount(merId, expiringTime);
                    tokenVo.setVphTokenExpiringCount(Tools.getInteger(vphTokenExpiringCount)-Tools.getInteger(vphTokenExpirdCount));
                }
            }
        }
        return tokenVo;
    }

    /**
     * 查询功能模块即将到期
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public ProductExpiredVo findProductExpired(Long merId){
        ProductExpiredVo productExpiredVo = new ProductExpiredVo();
        //功能产品即将到期列表
        List<String> productExpiringList = new ArrayList<>();
        //功能产品已经到期列表
        List<String> productExpiredList = new ArrayList<>();
        //设备产品即将到期列表
        List<String> deviceProductExpiringList = new ArrayList<>();
        //设备产品已经到期列表
        List<String> deviceProductExpiredList = new ArrayList<>();

        Integer now = DateUtil.getNowTime();
        //查询运营商开启的产品功能模块
        Object productSwitch = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.PRODUCT_SWITCH.getKey(), merId));
        if(productSwitch != null){
            List<String> productAuthList = JSONObject.parseArray(productSwitch.toString(), String.class);
            if(productAuthList != null && productAuthList.size() > 0){
               for(String produceCode : productAuthList){
                   //查询该功能模块价格
                   //产品按月购买价格
                   ProductPrice productPrice_month = productPriceMapper.selectByProductCodeAndAuthType(produceCode, DeviceAuthTypeEnum.DAT_MONTH.getId());
                   //产品按年购买价格价格
                   ProductPrice productPrice_year = productPriceMapper.selectByProductCodeAndAuthType(produceCode, DeviceAuthTypeEnum.DAT_YEAR.getId());
                   if(productPrice_month != null && Tools.getDouble(productPrice_month.getPrice()) > 0
                        && productPrice_year != null && Tools.getDouble(productPrice_year.getPrice()) > 0){ //有价格，需要查看授权
                       //查询当前运营商的产品功能配置
                       ProductAuth productAuth = productAuthMapper.selectByMerIdAndProductCode(merId, produceCode);
                       if(productAuth != null ){
                           //到期时间
                           Integer expireTime = Tools.getInteger(productAuth.getExpireTime());
                            if(expireTime.intValue() <= now.intValue()){//已经过期
                                ProductKeyEnum productKeyEnum = ProductKeyEnum.getValue(produceCode);
                                if(productKeyEnum != null){
                                    productExpiredList.add(productKeyEnum.getDesc());
                                }
                            }else if(expireTime.intValue() > now.intValue() && expireTime.intValue() <= now.intValue() + 604800){//表示即将到期（7天内）
                                ProductKeyEnum productKeyEnum = ProductKeyEnum.getValue(produceCode);
                                if(productKeyEnum != null){
                                    productExpiringList.add(productKeyEnum.getDesc());
                                }
                            }
                       }else{//表示未购买授权
//                           ProductKeyEnum productKeyEnum = ProductKeyEnum.getValue(produceCode);
//                           if(productKeyEnum != null){
//                               productNameList.add(productKeyEnum.getDesc());
//                           }
                       }
                   }

                   //设备产品
                   //按月购买
                   DevicePrice devicePrice_month = devicePriceMapper.selectByAuthType(DeviceAuthTypeEnum.DAT_MONTH.getId(), produceCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                   //按年购买
                   DevicePrice devicePrice_year = devicePriceMapper.selectByAuthType(DeviceAuthTypeEnum.DAT_YEAR.getId(), produceCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                   if(devicePrice_month != null && Tools.getDouble(devicePrice_month.getPrice()) > 0
                           && devicePrice_year != null && Tools.getDouble(devicePrice_year.getPrice()) > 0) { //有价格，需要查看授权
                       //即将到期
                       DeviceAuthQuery deviceAuthQuery_expiring = new DeviceAuthQuery();
                       deviceAuthQuery_expiring.setMerId(merId);
                       deviceAuthQuery_expiring.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey()); //个人微信机器人
                       deviceAuthQuery_expiring.setProductCode(produceCode);
                       deviceAuthQuery_expiring.setExpireType(2);
                       deviceAuthQuery_expiring.setRelateDeviceFlag(1);//关联设备表查询
                       List<DeviceAuth> deviceAuthList_expiring = deviceAuthMapper.findByList(deviceAuthQuery_expiring);
                       if(deviceAuthList_expiring != null && deviceAuthList_expiring.size() > 0){
                           DeviceProductKeyEnum deviceProductKeyEnum = DeviceProductKeyEnum.getValue(produceCode);
                           if(deviceProductKeyEnum != null){
                               deviceProductExpiringList.add(deviceProductKeyEnum.getDesc());
                           }
                       }
                       //已经到期
                       DeviceAuthQuery deviceAuthQuery_expired = new DeviceAuthQuery();
                       deviceAuthQuery_expired.setMerId(merId);
                       deviceAuthQuery_expired.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey()); //个人微信机器人
                       deviceAuthQuery_expired.setProductCode(produceCode);
                       deviceAuthQuery_expired.setExpireType(0); //已经到期
                       deviceAuthQuery_expired.setRelateDeviceFlag(1);//关联设备表查询
                       List<DeviceAuth> deviceAuthList_expired = deviceAuthMapper.findByList(deviceAuthQuery_expired);
                       if(deviceAuthList_expired != null && deviceAuthList_expired.size() > 0){
                           DeviceProductKeyEnum deviceProductKeyEnum = DeviceProductKeyEnum.getValue(produceCode);
                           if(deviceProductKeyEnum != null){
                               deviceProductExpiredList.add(deviceProductKeyEnum.getDesc());
                           }
                       }
                   }
               }
            }
        }
        productExpiredVo.setProductExpiringList(productExpiringList);
        productExpiredVo.setProductExpiredList(productExpiredList);
        productExpiredVo.setDeviceProductExpiringList(deviceProductExpiringList);
        productExpiredVo.setDeviceProductExpiredList(deviceProductExpiredList);
        return productExpiredVo;
    }

    /**
     * 查询机器人即将到期
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public DeviceExpiredVo findDeviceExpired(Long merId){
        DeviceExpiredVo deviceExpiredVo = new DeviceExpiredVo();
        int offLineCount = 0;
        int expiredCount = 0;
        //查询运营商开启的产品功能模块
        Object productSwitch = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_SWITCH.getKey(), merId));
        if(productSwitch != null) {
            JSONArray productAuthArray = JSONObject.parseArray(productSwitch.toString());
            if (productAuthArray != null && productAuthArray.size() > 0) {
                if (productAuthArray.contains(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {//开启个人微信模块

                    //查询即将到期
                    DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
                    deviceWechatInfoQuery.setMerId(merId);
                    deviceWechatInfoQuery.setExpireType(2); //即将到期
                    List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
                    if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
                        expiredCount = deviceWechatInfoList.size(); //即将到期数
                    }

                    DeviceWechatInfoQuery deviceWechatInfoQuery_notExpired = new DeviceWechatInfoQuery();
                    deviceWechatInfoQuery_notExpired.setMerId(merId);
                    deviceWechatInfoQuery_notExpired.setExpireType(1); //即将到期
                    List<DeviceWechatInfo> deviceWechatInfoList_notExpired = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery_notExpired);
                    if(deviceWechatInfoList_notExpired != null && deviceWechatInfoList_notExpired.size() > 0){
                        for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList_notExpired) {
                            //从缓存redis中查询机器人的心跳信息
                            boolean onlineFlag = false; //在线标志
                            //从缓存中换取个人微信PC端信息
                            Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoPcWeChatCacheDto.class);
                            //手机端个人微信信息不为空
                            if(deviceInfoPcWeChatCacheDto != null){
                                //获取最新心跳时间
                                Integer lastHeartBeatTime = deviceInfoPcWeChatCacheDto.getLastHeartBeatTime();
                                if(lastHeartBeatTime != null){
                                    //判断在线（少于5分钟表示在线）
                                    if(DateUtil.getNowTime() - lastHeartBeatTime.intValue()  < Const.Device.HEART_BEAT_OFF_LINE_TIME.intValue()){
                                        onlineFlag = true; //在线
                                    }
                                }
                            }

                            //从缓存中获取个人微信手机端信息
                            Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWeChatCacheDto.class);
                            //手机端个人微信信息不为空
                            if(deviceInfoMobileWeChatCacheDto != null){
                                //获取最新心跳时间
                                Integer lastHeartBeatTime = deviceInfoMobileWeChatCacheDto.getLastHeartBeatTime();
                                if(lastHeartBeatTime != null){
                                    //判断在线（少于5分钟表示在线）
                                    if(DateUtil.getNowTime() - lastHeartBeatTime.intValue()  < Const.Device.HEART_BEAT_OFF_LINE_TIME.intValue()){
                                        onlineFlag = true; //在线
                                    }
                                }
                            }
                            //机器人不在线，则在线机器人数+1
                            if(!onlineFlag){
                                offLineCount ++ ; //
                            }
                        }
                    }
                }
            }
        }
        deviceExpiredVo.setExpiredCount(expiredCount);
        deviceExpiredVo.setOffLineCount(offLineCount);
        return deviceExpiredVo;
    }

    /**
     * 查询好友请求数
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public FriendRequestVo findFrindRequestCount(Long merId){
        FriendRequestVo friendRequestVo = new FriendRequestVo();
        //查询运营商开启的设备功能模块
        Object deviceSwitch = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_SWITCH.getKey(), merId));
        if(deviceSwitch != null) {
            JSONArray deiviceAuthArray = JSONObject.parseArray(deviceSwitch.toString());
            if (deiviceAuthArray != null && deiviceAuthArray.size() > 0) {
                if (deiviceAuthArray.contains(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {//开启个人微信模块
                    FriendRequestQuery friendRequestQuery = new FriendRequestQuery();
                    friendRequestQuery.setMerId(merId);
                    friendRequestQuery.setStatus(0);
                    Page<FriendRequestInfoVo> friendRequestInfoVoPage = friendRequestService.findFriendRequestList(friendRequestQuery, null);
                    if(friendRequestInfoVoPage != null ){
                        friendRequestVo.setFriendRequestCount(friendRequestInfoVoPage.getTotal());
                    }
                }
            }
        }
        return friendRequestVo;
    }

    /**
     * 账户充值
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param rechargeDto
     * @return null
     */
    public RechargeVo recharge(RechargeDto rechargeDto){
        RechargeVo rechargeVo = new RechargeVo();
        //业务号
        String trandeno = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        //当前时间
        Integer now = DateUtil.getNowTime();

        if(rechargeDto.getPayType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付类型");
        }

        if(Tools.getDouble(rechargeDto.getAmount()) <= 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "充值金额不正确");
        }

        //判断支付类型
        if(rechargeDto.getPayType().intValue() == PaymentTypeEnum.PAY_ALIPAY.getId().intValue()) {//支付宝支付
            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(rechargeDto.getMerId());
            alipayDetail.setTradeno(trandeno);
            alipayDetail.setType(AlipayTypeEnum.BALANCE_RECHARGE.getId()); //账户充值
            //业务信息
            RechargeBusinessInfo rechargeBusinessInfo = new RechargeBusinessInfo();
            rechargeBusinessInfo.setAmount(rechargeDto.getAmount());
            alipayDetail.setBusinessInfo(JSONObject.toJSONString(rechargeBusinessInfo));
            alipayDetail.setAmount(rechargeDto.getAmount());
            alipayDetail.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId()); //等待付款
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);
            if (rechargeDto.getBizDetailType() !=null && rechargeDto.getBizDetailType().equals(1)) {
                alipayDetail.setSubtype(AlipaySubtypeEnum.CONTRACT_SIGN_RECHARGE.getKey());
            }

            //请求支付宝申请订单
            AlipayDetailCreateDto alipayDetailCreateDto = new AlipayDetailCreateDto();
            alipayDetailCreateDto.setOutTradeNo(alipayDetail.getTradeno());
            alipayDetailCreateDto.setTotalAmount(alipayDetail.getAmount());
            alipayDetailCreateDto.setSubject(AlipayTypeEnum.BALANCE_RECHARGE.getDesc());
            String alipayUrl = alipayDetailService.createAlipayDetail(alipayDetailCreateDto);
            if(StringUtils.isNotBlank(alipayUrl)){
                alipayDetail.setAlipayUrl(alipayUrl);
                //插入支付宝账单
                alipayDetailMapper.insertSelective(alipayDetail);

                rechargeVo.setAlipayUrl(uzaiConsoleSysConfig.getAlipayPaypageUrl()+"?id=" + alipayDetail.getId());

            }else{
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝失败");
            }
        }
        return rechargeVo;
    }

    /**
     * 账户提现
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalDto
     * @return null
     */
    @Transactional
    public void takeBal(TakeBalDto takeBalDto){

        if(StringUtils.isBlank(takeBalDto.getCode())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码");
        }

        Long merId = takeBalDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if(!uzaiConsoleSysConfig.getDefaultPassword().equals(takeBalDto.getCode())){
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.CMSTYPE_BAlANCE_TAKE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }
            //验证码是否正确
            if (!codeByRedis.equals(takeBalDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(takeBalDto.getCode())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.CMSTYPE_BAlANCE_TAKE.getDesc(), merchant.getMobile()));
        }

        //业务号
        String trandeno = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        //当前时间
        Integer now = DateUtil.getNowTime();

        if(StringUtils.isBlank(takeBalDto.getAlipayUserId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付宝账号");
        }

        if(StringUtils.isBlank(takeBalDto.getAlipayUserName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付宝真实姓名");
        }

        if(takeBalDto.getAmount() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入提现金额");
        }

        if(Tools.getDouble(takeBalDto.getAmount()).doubleValue() < 0.1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现金额最小为0.1元");
        }

        //判断账号余额是否足够
        Double balance = Tools.getDouble(merchant.getBalance());
        if(balance.doubleValue() < Tools.getDouble(takeBalDto.getAmount()).doubleValue()){ //不够支付
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现金额超过了账户余额");
        }

        //请求支付宝申请订单
        TransUniTransferDto transUniTransferDto = new TransUniTransferDto();
        transUniTransferDto.setOutTradeNo(trandeno);
        transUniTransferDto.setTotalAmount(takeBalDto.getAmount());
        transUniTransferDto.setSubject(AlipayTypeEnum.BALANCE_TAKEBAL.getDesc());
        transUniTransferDto.setAlipayUserId(takeBalDto.getAlipayUserId());
        transUniTransferDto.setAlipayUserName(takeBalDto.getAlipayUserName());
        Boolean result = alipayDetailService.transUniTransfer(transUniTransferDto);
        if(result){//转账成功
            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(takeBalDto.getMerId());
            alipayDetail.setTradeno(trandeno);
            alipayDetail.setType(AlipayTypeEnum.BALANCE_TAKEBAL.getId()); //余额提现
            //业务信息
            TakeBalBusinessInfo takeBalBusinessInfo = new TakeBalBusinessInfo();
            takeBalBusinessInfo.setAmount(takeBalDto.getAmount());
            takeBalBusinessInfo.setAlipayUserId(takeBalDto.getAlipayUserId());
            takeBalBusinessInfo.setAlipayUserName(takeBalDto.getAlipayUserName());
            alipayDetail.setBusinessInfo(JSONObject.toJSONString(takeBalBusinessInfo));
            alipayDetail.setAmount(takeBalDto.getAmount());
            alipayDetail.setStatus(AlipayStatusEnum.TRADE_SUCCESS.getId()); //付款成功
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);
            alipayDetailMapper.insertSelective(alipayDetail);

            //修改账户余额
            merchant.setBalance(balance - alipayDetail.getAmount());
            merchant.setUpdateTime(now);
            int i = merchantMapper.updateBalance(merchant);
            if(i != 1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改账户余额失败");
            }

            //添加账户明细
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(alipayDetail.getAmount());
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.BALANCE_TAKEBAL.getId()); //账户余额提现
            merAccDetail.setTradeno(alipayDetail.getTradeno());
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            int j = merAccDetailMapper.insert(merAccDetail);
            if(j != 1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改账户余额失败");
            }
        }
    }

    @Override
    public DingExclusiveGroupConfig queryDingDingExclusiveGroupQrCode(Long merId) {

        DingExclusiveGroupConfig dingExclusiveGroupConfig = new DingExclusiveGroupConfig();

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DINGDING_EXCLUSIVE_GROUP_QRCODE_CONFIG.getValue());
        //查询配置表中有无二维码配置，没有就创建
        if (merBaseConfig != null) {
            dingExclusiveGroupConfig = JSONObject.parseObject(merBaseConfig.getVal(), DingExclusiveGroupConfig.class);
        } else {
            try {

                //获取创建钉钉群的基本参数
                Object o = redisTemplate.opsForValue().get(RedisCacheKeyEnum.DING_DING_EXCLUSIVE_GROUP.getKey());
                if (o == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "获取钉钉专属服务群配置失败");
                }
                ExclusiveGroupOptDto ex = JSONObject.parseObject(o.toString(), ExclusiveGroupOptDto.class);



                //获取token
//                String accessToken=null;
//                Object o1 = redisTemplate.opsForValue().get(RedisCacheKeyEnum.DING_TALK_OAUTH_ACCESS_TOKEN.getKey());
//                if(o1==null){
//                    com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
//                            .setAppKey(ex.getAppKey())
//                            .setAppSecret(ex.getAppSecret());
//                    GetAccessTokenResponse getAccessTokenResponse = dingTokenClient.getAccessToken(getAccessTokenRequest);
//                    if(getAccessTokenResponse==null||getAccessTokenResponse.getBody()==null){
//                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "获取accessToken失败");
//                    }
//                     accessToken = getAccessTokenResponse.getBody().getAccessToken();
//                    redisTemplate.opsForValue().set(RedisCacheKeyEnum.DING_TALK_OAUTH_ACCESS_TOKEN.getKey(),accessToken,100, TimeUnit.MINUTES);
//                }else {
//                    accessToken=o1.toString();
//                }

                String accessToken = dingExclusiveGroupUtils.getAccessToken(ex.getAppKey(),ex.getAppSecret());



                //获取专属群名称
                Merchant merchant = merchantMapper.selectById(merId);
                if(merchant==null){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "获取运营商信息失败");
                }
                String groupName=ex.getGroupName().replace("[运营商账号]",Tools.getStr(merchant.getMobile()));

                //创建钉钉专属群
                CreateGroupHeaders createGroupHeaders = new CreateGroupHeaders();
                createGroupHeaders.xAcsDingtalkAccessToken = accessToken;
                CreateGroupRequest createGroupRequest = new CreateGroupRequest()
                        .setGroupBizId(String.valueOf(merId))
                        .setOpenTeamId(ex.getOpenTeamId())
                        .setOpenGroupSetId(ex.getOpenGroupId())
                        .setGroupName(groupName)
                        .setOwnerStaffId(ex.getGroupMasterId())
                        .setMemberStaffIds(ex.getGroupMemberIds());
                CreateGroupResponse groupWithOptions = dingGroupClient.createGroupWithOptions(createGroupRequest, createGroupHeaders, new RuntimeOptions());
                if (groupWithOptions == null || groupWithOptions.getBody() == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "创建钉钉专属群失败");
                }

                //设置返回参数
                dingExclusiveGroupConfig.setOpenConversationId(groupWithOptions.getBody().getOpenConversationId());
                dingExclusiveGroupConfig.setGroupUrl(groupWithOptions.getBody().getGroupUrl());
                //默认设置一个最大的时间戳（不过期）
                dingExclusiveGroupConfig.setExpireTime(2147483647);
                dingExclusiveGroupConfig.setIfJoinGroup(0);

                //返回参数配置数据入库
                int nowTime = DateUtil.getNowTime();
                merBaseConfig = new MerBaseConfig();
                merBaseConfig.setId(IdWorker.getId());
                merBaseConfig.setMerId(merId);
                merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
                merBaseConfig.setKey(MerConfigKeyEnum.DINGDING_EXCLUSIVE_GROUP_QRCODE_CONFIG.getValue());
                merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(dingExclusiveGroupConfig)));
                merBaseConfig.setCreateTime(nowTime);
                merBaseConfig.setUpdateTime(nowTime);
                merBaseConfigMapper.insert(merBaseConfig);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return dingExclusiveGroupConfig;
    }

    @Override
    public boolean checkJoinGroup(Long merId) {
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.DINGDING_EXCLUSIVE_GROUP_QRCODE_CONFIG.getValue());
        if (Objects.isNull(merBaseConfig)) {
            return false;
        }
        DingExclusiveGroupConfig dingExclusiveGroupConfig = JSONObject.parseObject(merBaseConfig.getVal(), DingExclusiveGroupConfig.class);
        if (Objects.isNull(dingExclusiveGroupConfig)) {
            return false;
        }

        return Objects.equals(dingExclusiveGroupConfig.getIfJoinGroup(), 1);
    }

    @Override
    public ProfitVo findProfitV2(Long merId) {
        RealTimeOverviewReportFeignDto realTimeOverviewReportFeignDto = new RealTimeOverviewReportFeignDto();
        realTimeOverviewReportFeignDto.setMerId(merId);
        UzaiRespVo<ProfitVo> dashboard = uzaiReportServerFeignService.dashboard(realTimeOverviewReportFeignDto);
        return dashboard.getData();
    }
}
